import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:http/http.dart';

import '../constants/api_constants.dart';

class Index extends StatefulWidget {
  const Index({super.key});

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {
  List carousels = [];
  List menuItems = [];
  List activities = [];

  @override
  void initState() {
    (() async {
      var s = FlutterSecureStorage();
      var token = await s.read(key: 'userToken');
      var url = APIConstants.indexData;
      var res = await get(Uri.parse(url), headers: {'token': ?token});
      var data = jsonDecode(res.body);
      setState(() {
        carousels.addAll(data['carousels']);
        menuItems.addAll(data['menuItems']);
        activities.addAll(data['activities']);
      });
    })();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          //F1:轮播广告
          SizedBox(
            width: double.infinity,
            height: 160,
            //Flutter官方没有提供Swiper组件，这里使用三方库flutter_swiper_view
            child: Swiper(
              itemCount: carousels.length,
              itemBuilder: (context, i) => Image.network(
                APIConstants.base + carousels[i]['pic'],
                fit: BoxFit.fill,
              ),
              // pagination: SwiperPagination(),
              // controller: SwiperController(),
              autoplay: true,
            ),
          ),
          //F2:十宫格
          //F3:商业服务
          //F4:社区活动
        ],
      ),
    );
  }
}
